The keyword LEFT JOIN returns all records from the left table (table1) and the corresponding records from the right table (table2).
The result will be 0 entries on the right side if there is no match.
SELECT column_name(s)
FROM table1
LEFT JOIN table2
ON table1.column_name = table2.column_name
In this tutorial we will use the famous example database "Northwind".
Below is a sample from the table "Customers" ("Customers"):
CustomerID | CustomerName | ContactName | Address | City | PostalCode | Country |
---|---|---|---|---|---|---|
1 | Alfreds Futterkiste | Maria Anders | Obere Str. 57 | Berlin | 12209 | Germany |
2 | Ana Trujillo Emparedados y helados | Ana Trujillo | Avda. de la Constitución 2222 | México D.F. | 5021 | Mexico |
3 | Antonio Moreno Taquería | Antonio Moreno | Mataderos 2312 | México D.F. | 5023 | Mexico |
4 | Around the Horn | Thomas Hardy | 120 Hanover Sq. | London | WA1 1DP | UK |
5 | Berglunds snabbköp | Christina Berglund | Berguvsvägen 8 | Luleå | S-958 22 | Sweden |
And the sample from the table "Orders" ("Orders"):
ProductID | OrderID | CustomerID | EmployeeID | OrderDate | ShipperID |
---|---|---|---|---|---|
1 | 10248 | 90 | 5 | 1996-07-04 | 3 |
2 | 10249 | 81 | 6 | 1996-07-05 | 1 |
3 | 10250 | 34 | 4 | 1996-07-08 | 2 |
4 | 10251 | 84 | 3 | 1996-07-08 | 1 |
5 | 10252 | 76 | 4 | 1996-07-09 | 2 |
The following SQL statement will select all customers and any orders they may have:
Run SQLSELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders ON Customers.CustomerID = Orders.CustomerID
ORDER BY Customers.CustomerName